package book;

import utils.AnalyzingBook;

import constant.Constant;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Scanner;


public class Library {
    private Book[] books;//当前图书数组
    private int bookCount = 0;//实际存储的图书数量
    AnalyzingBook analyzingBook = new AnalyzingBook();//书籍解析相关类实例

    private static Library library;

    Scanner sc = new Scanner(System.in);

    //在 Library 类一创建时就将文件内图书信息加载进 Library 对象中去
    private Library() {
        loadAllBook();
    }

    //为 Library 类创建懒汉式单例模式
    public static Library getLibrary() {
        if(library == null) {
            library = new Library();
        }
        return library;
    }

    public int getBookCount() {
        return bookCount;
    }

    private void storeBook() {
        analyzingBook.storeObject(books,"allbooks.txt");
    }

    private void loadAllBook() {
        Book[] allBooks = analyzingBook.loadObject("allbooks.txt");
        books = new Book[Constant.CAPACITY];
        if(allBooks == null) {
            return;
        } else {
            if(allBooks.length > Constant.CAPACITY) {
                books = new Book[allBooks.length];
            }
            for (int i = 0; i < allBooks.length; i++) {
                books[i] = allBooks[i];
            }
            bookCount = allBooks.length;
        }
    }

    //上架图书
    public void addBook(Book newBook) {
        //如何扩容?
        if(bookCount == books.length) {
            System.out.println("书架已满,无法上架图书!");
            return;
        } else {
            newBook.setBookId(bookCount+1);// 为新书设置图书Id
            //将新书存入文件中
            books[bookCount++] = newBook;
            storeBook();
            System.out.println("图书" + newBook.getTitle() + "上架成功!");
        }
    }

    //展示馆内所有图书
    public void displayBooks() {
        System.out.println("馆内所有书籍如下:");
        loadAllBook();

        System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------");
        for (int i = 0; i < bookCount; i++) {
            System.out.println(books[i]);
        }
        System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------");
    }

    //根据图书Id查找图书
    public Book searchBook(int bookId) {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            if(bookId == books[i].getBookId()) {
                return books[i];
            }
        }
        return null;
    }

    //根据书名查找图书
    public Book searchBook(String title) {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            if(books[i].getTitle().equals(title)) {
                return books[i];
            }
        }
        return null;
    }

    //根据书名查找图书
    public void searchBook() {
        System.out.println("请输入你要查找的图书名称:");
        String title = sc.next();

        Book book = searchBook(title);
        if(book == null) {
            System.out.println("没有查找到你要查找的图书!");
            return;
        } else {
            System.out.println("找到了,你要查找的书籍信息如下:");
            System.out.println(book);
        }
    }

    //获取图书在 books 组中的位置
    private int bookReturnIndex(Book book) {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            //因为没有为 book 类写 equal 方法,只能用图书Id来比较
            if(books[i].getBookId() == book.getBookId()) {
                return i;
            }
        }
        return -1;
    }

    //更新图书
    public void updataBook(Book book) {
        storeBook();
        System.out.println("更新成功,更新后书籍信息如下:");
        System.out.println(book);
    }

    //下架图书
    public void removeBook(Book book) {
        int index = bookReturnIndex(book);
        if(index == -1) {
            System.out.println("没有你要下架的图书!");
            return;
        }
        for (int i = index; i < bookCount-1; i++) {
            books[i] = books[i+1];
        }
        books[bookCount-1] = null;
        bookCount--;
        for (int i = index; i < bookCount; i++) {
            books[i].decreaseBookId();
        }
        storeBook();
        System.out.println("移除成功!");
    }

    //查看所有图书借阅次数
    public void borrowCount(){
        loadAllBook();
        System.out.println("----------------------------------");
        for (int i = 0; i < bookCount; i++) {
            System.out.println("图书:" + books[i].getTitle() + " 借阅次数:" + books[i].getBorrowCount());
        }
        System.out.println("----------------------------------");
    };

    //查询最受欢迎的前k本书
    public void generateBook(int k) {
        //加载已有的全部书籍
        loadAllBook();
        //
        Book[] tmp = new Book[bookCount];
        for (int i = 0; i < bookCount; i++) {
            tmp[i] = books[i];
        }
        //在 Book 类中实现 Comparable 接口根据借阅次数来排序
        Arrays.sort(tmp);
        //打印最受欢迎前k本书
        System.out.println("-------------------------------------------------");
        System.out.println("最受欢迎书籍如下:");
        for (int i = 0; i < k; i++) {
            System.out.println("书名:" + tmp[i].getTitle() + " 作者:" + tmp[i].getAuthor() + " 借阅次数:" + tmp[i].getBorrowCount());
        }
        System.out.println("-------------------------------------------------");
    }

    //查看库存状态
    public void checkInventoryStatus() {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            String staus = books[i].getBorrowedStatus() ? "已借出" : "在馆";
            System.out.println("书名:" + books[i].getTitle() + " 状态:" + staus);
        }
    }

    //移除上架超过一年的图书
    public void checkAndRemoveOldBooks() {
        loadAllBook();
        // 获取当前时间戳
        long currentTimestamp = System.currentTimeMillis();

        // 将当前时间戳转换为 LocalDate
        LocalDate currentDate = Instant.ofEpochMilli(currentTimestamp)
                .atZone(ZoneId.systemDefault())
                .toLocalDate();

        boolean flg = false;
        for (int i = 0; i < getBookCount(); i++) {
            Book book = books[i];
            //获取当前书籍的上架时间
            LocalDate specifiedDate = book.getShelfDate();

            // 计算两个日期之间的差值（以年为单位）
            long yearsBetween = ChronoUnit.YEARS.between(specifiedDate, currentDate);

            if(yearsBetween >= 1) {
                System.out.print("图书 " + book.getTitle() + " 已经上架超过一年，是否移除？ (y/n)：");
                String response = sc.next();
                if (response.equalsIgnoreCase("y")) {
                    //确认删除调用remove方法进行删除
                    removeBook(book);
                    i--;  // 因为后面的书已经向前移动，所以要重新检查当前索引位置
                }
                flg = true;
            }
        }
        if(!flg) {
            System.out.println("没有上架超过一年的图书！");
        }
        storeBook();
    }

    //借阅书籍
    public void borrowBook(int bookId) {
        //更改图书借阅状态和次数
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if(book.getBookId() == bookId) {
                book.setBorrowedStatus(true);
                book.incrementBorrowCount();
            }
        }
        //存入文件信息
        storeBook();
    }

    //归还书籍
    public void returnBook(int bookId) {
        loadAllBook();

        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if(book.getBookId() == bookId) {
                book.setBorrowedStatus(false);
            }
        }

        storeBook();
    }



    public void exit() {
        System.out.println("退出系统!");
        System.exit(0);
    }

}
